//===============商品商城管理.js


//============全部商品列表===============

function allGoodsList(evt) {
    console.log(evt);

    xloadList(evt, function (filter) {
        //前置条件
        filter.saled = 1;
        filter.enabled = 1;
        //过期时间大于当前时间
        filter.expiry = [formatDate(new Date()), formatDate(new Date("3090-12-12 00:00:00"))];
        if (filter.review_status == null || filter.review_status.length == 0) {
            filter.review_status = ["1", "2", "3", "4"];
        }
        filter.type = ["0", "3"];
    });

}

//============全部商品列表--添加商品弹框列表加载事件===========

function notApprovedGoodsList(evt) {
    console.log(evt);

    xloadList(evt, function (filter) {
        //前置条件
        filter.saled = 1;
        filter.enabled = 1;
        filter.expiry = [formatDate(new Date()), formatDate(new Date("3090-12-12 00:00:00"))];
        filter.review_status = "0";
        filter.type = ["0", "3"];
    });

}

//==========全部商品列表-- 单元格渲染事件
function cellRender(evt) {
    let {components, col, row, formatText} = evt.data;
    let value = row[col.key];

    // 订单状态
    if (col.key === 'review_status') {
        var color = '';
        switch (value) {
            case '1':
                color = '#1E9FFF';
                break;
            case '2':
                color = '#ffb800';
                break;
            case '3':
                color = '#009688';
                break;
            case '4':
                color = '#FF5722';
                break;
        }
        components[0] = {
            type: 'Tag',
            props: {
                text: formatText,
                color
            }
        };
    }

}


/**
 * 前台自定义服务
 */
function xloadList(evt, call) {
    var list = h3ui.widgets[evt.node.id];

    var filter = evt.data.filter;

    if (call != undefined && call instanceof Function) {

        var callFilter = JSON.parse(JSON.stringify(filter || {}));

        call(callFilter);

        filter = callFilter;
    }

    var pageIndex = evt.data.pageIndex;
    var pageSize = evt.data.pageSize;


    var schemaCode = list.props.bindingModel.schemaCode;

    h3ui.models[schemaCode].listBO({pageIndex, pageSize, filter}).then(res => {

        list.props.dataSource = res;

        list.props.selectedRowKeys = [];
        list.props.selectedRow = [];

    })
}


//=======页面初始化事件 ==============
function myPageInit() {
    // 全部商品列表,查询字段里,审批状态去掉 未审核
    if (h3ui.widgets.Select47) {
        h3ui.widgets.Select47.props.options.splice(0, 1);
    }


    //过期时间 前置条件  大于当前时间 , 通过页面初始化做, 目前控制列表的查询条件有:  待审批列表,  已审核通过列表 ,  上下架列表(mall_sales)
    var expiry = [formatDate(new Date()), formatDate(new Date("3090-12-12 00:00:00"))];
    //待审批里的
    h3ui.widgets.FormModelItem147.props.defaultValue = expiry;
    //已审核通过的
    h3ui.widgets.FormModelItem148.props.defaultValue = expiry;
    //上下架列表的
    h3ui.widgets.FormModelItem149.props.defaultValue = expiry;


}


//====================


//商品添加并提交审核
function mallAddAndReview() {
    mallAdd({reviewStatus: 2});
}


// 已审核列表-打开上架对话框
function openModalSaled(evt) {
    var selectListId = "FormList-saled";

    if (h3ui.widgets[selectListId].props.selectedRowKeys.length == 0) {
        h3ui.$message.error("请选择一行数据");
        return false;
    }
    h3ui.widgets.RadioGroup5.props.value = 1;
    openModal(evt);
}

/**
 * 已审核列表
 * 上架并修改是否精选
 *
 */
function upSaledAndFeatured() {
    var selectList = "FormList-saled";
    var reloadList = "FormList13";

    var closeModalId = "Modal10,Modal-saledandFeatured";
    var mallFeatured = h3ui.widgets.RadioGroup5.props.value;


    var param = {"saled": 1, "mallFeatured": mallFeatured};

    toCallService({
        formListId: selectList,
        reloadListId: reloadList,
        serviceName: "upSaledAndFeatured",
        msg: "",
        closeModalId: closeModalId,
        param: param,
    });

}


/**
 *  待审批列表
 *  审批业务服务: 审批或驳回  toReview  2->3,4
 */
function toReview() {

    var selectList = "FormList15";
    var closeModalId = "Modal8";

    if (h3ui.widgets[selectList].props.selectedRowKeys.length != 1) {
        h3ui.$message.error("只能选择一行数据");
        return false;
    }

    var reviewStatus = h3ui.widgets.RadioGroup3.props.value;
    var reviewContent = h3ui.widgets.Textarea7.props.value;

    if (reviewStatus == 4 && !reviewContent) {
        h3ui.$message.error("请填写驳回理由");
        return false;
    }

    var msg = reviewStatus == 3 ? "已审核" : "驳回";

    var param = {"reviewContent": reviewContent, "reviewStatus": reviewStatus};

    toCallService({
        formListId: selectList,
        reloadListId: selectList,
        serviceName: "toReview",
        msg: msg,
        closeModalId: closeModalId,
        param: param,
    });


}

//待审批列表 - 打开审批对话框
function openModalToReview(evt) {
    console.log(evt)
    if (h3ui.widgets.FormList15.props.selectedRowKeys.length == 0) {
        h3ui.$message.error("请选择一行数据");
        return false;
    }
    if (h3ui.widgets.FormList15.props.selectedRowKeys.length != 1) {
        h3ui.$message.error("只能选择一行数据");
        return false;
    }
    h3ui.widgets.RadioGroup3.props.value = 3;
    openModal(evt)

}

/**
 * 待审批列表- 审批单选显示 审批理由
 *
 */
function radioGroupClick(evt) {
    console.log(evt.node.props.value);

    var display = (evt.node.props.value == 3 ? "none" : "");
    console.log("display:", display);
    h3ui.widgets.Grid7.props.visible.display = display;
}


// 已审核列表-下架
function downSaled() {

    toCallService({
        formListId: "FormList-saled",
        reloadListId: "FormList13",
        serviceName: "downSaled",
        msg: "下架",
        closeModalId: "Modal10",
        param: {},
    });


}


// 商品添加 0->1
function mallAdd(evt) {
    var val = h3ui.widgets.InputNumber35.props.value;
    val = Number.parseFloat(val);
    if (isNaN(val) || val < 0) {
        h3ui.$message.info("请填写调整比例并且大于0");
        return false;
    }

    toCallService({
        formListId: "FormList9",
        reloadListId: "FormList7",
        serviceName: "mallAdd",
        msg: "",
        closeModalId: "Modal4,Modal1",
        param: {"adjustRatio": val, "reviewStatus": evt.reviewStatus || 1},
    });
}

// 打开商品比例调整
function toUpdateAdjustRatioModel(evt) {
    console.log(evt);
    if (h3ui.widgets.FormList7.props.selectedRowKeys.length == 0) {
        h3ui.$message.error("请选择一行或多行数据");
        return false;
    }
    openModal(evt);
}


// 商品比例调整
function updateAdjustRatio(evt) {

    var formListId = 'FormList7';

    var val = h3ui.widgets.InputNumber33.props.value;

    toCallService({
        formListId: formListId,
        reloadListId: "FormList7",
        serviceName: "updateAdjustRatio",
        msg: "",
        closeModalId: evt.node.id,
        param: {adjustRatio: val},
    });


}


// 商品上架(驳回->审核中) 4->2
function mallReject2Review(evt) {

    var formListId = 'FormList7';

    var rows = h3ui.widgets[formListId].props.selectedRow;
    var row = rows.filter(a => a.review_status != 4);

    if (row.length > 1) {
        h3ui.$message.error("非已驳回的商品不能申请手动上架为审核中");
    } else {
        toCallService({
            formListId: formListId,
            reloadListId: "FormList7",
            serviceName: "mallReject2Review",
            msg: "",
            closeModalId: "",
            param: {},
        });
    }


}

// 商品撤销 (1,2,3,4) -> 0
function mallRevoke(evt) {

    var formListId = 'FormList7';

    var rows = h3ui.widgets[formListId].props.selectedRow;
    var row = rows.filter(a => a.review_status == 3).map(a => a.id).find(a => a);
    var str = "";
    if (row) {
        str = "商品" + row + "审核已通过, 撤销后该商品会在商城下架, 是否继续?";//
    } else {
        str = "是否撤销?";
    }

    toCallService({
        formListId: formListId,
        reloadListId: "FormList7",
        serviceName: "mallRevoke",
        msg: str,
        closeModalId: "",
        param: {},
    });
}

/**
 * 商品已驳回和待提交 -> 审核中 1,4 -> 2
 *
 */
function mallReview(evt) {

    var formListId = 'FormList7';

    var rows = h3ui.widgets[formListId].props.selectedRow;
    var row = rows.find(a => a.review_status == 3 || a.review_status == 2);

    if (row) {
        var str = "商品" + row.id + "的状态为" + (row.review_status == 3 ? "已审核" : "审核中") + ", 无需提交审核!";
        h3ui.$message.error(str);
    } else {

        toCallService({
            formListId: formListId,
            reloadListId: formListId,
            serviceName: "mallReview",
            msg: "",
            closeModalId: "",
            param: {},
        });
    }


}


// 打开添加商品设置对话框
function openModal4() {
    var length = h3ui.widgets.FormList9.props.selectedRowKeys.length;

    if (length == 0) {
        h3ui.$message.error("请选择一行或多行数据");
        return;
    }

    h3ui.widgets.Modal4.props.visible = true;
}

/**
 * 打开对话框,按钮的id 设置为 xxx_Modalx 如: Buttons_Modal1
 */
function openModal(evt) {
    debugger;
    var modalId = evt.node.id.split("_")[1];
    h3ui.widgets[modalId].props.visible = true;
}

/**
 * 关闭对话框
 */
function closeModal(evt) {
    var modalId = evt.node.id.split("_")[1];
    h3ui.widgets[modalId].props.visible = false;
}

// ============公共方法=======


//触发列表刷新事件
function reloadList(fromListId) {
    doReloadList({pageIndex: 1, node: {id: fromListId}});
}

//标签页切换 刷新列表, 要求 标签页id 是 "xxx"+"_"+listid
function tabLoadList(evt) {
    doReloadList({node: {id: evt.data.activeKey.split("_")[1]}});
}


//列表刷新
function doReloadList(evt) {
    var list = h3ui.widgets[evt.node.id];

    var queryId = list.childIds.find(a => a.includes("ModelQueryForm"));

    var filter = h3ui.widgets[queryId].props.value || {};

    var pageId = list.childIds.find(a => a.includes("Pagination"));

    var pageIndex = h3ui.widgets[pageId].props.current;
    var pageSize = h3ui.widgets[pageId].props.pageSize;


    list.emit("load", {pageIndex, pageSize, filter});

    list.props.selectedRowKeys = [];

}

/**
 * 提交自定义业务服务
 * map:{formListId : "", // select列表id
 * 	reloadListId : "",// 重新加载的list
 * 	serviceName : "",// 服务名称
 * 	msg :"", // 提示内容
 * 	closeModalId:"", // 需要关闭的对话框id, 多个用","隔开
 * 	param : {} // 提交参数 
 * }
 */
function toCallService(map) {

    var selectKeys = h3ui.widgets[map.formListId].props.selectedRowKeys;
    let length = selectKeys.length;
    if (length == 0) {
        h3ui.$message.error("请选择一行数据");
        return false;
    }
    map.param.ids = selectKeys;

    h3ui.$confirm({
        title: map.msg || '确认提交吗',
        onOk() {
            h3ui.services[map.serviceName](map.param).then(res => {
                if (res.success) {
                    h3ui.$message.success('提交成功');

                    if (map.reloadListId) {
                        reloadList(map.reloadListId);
                    }

                    if (map.closeModalId) {
                        map.closeModalId.split(",").forEach(a => {
                            if (a) h3ui.widgets[a].props.visible = false;
                        })
                    }

                } else {
                    h3ui.$message.error(res.errMessage || '提交失败');
                }
            })
        }
    });
}


function queryLoadBrandList() {

    reloadList("FormList16");

}

function loadBrandList(evt) {
    console.log("loadBrandList", evt);

    var list = h3ui.widgets[evt.node.id];
    var filter = h3ui.widgets[list.childIds[0]].props.value;
    var pageIndex = evt.pageIndex;
    var pageSize = 10;
    if (!pageIndex) {
        pageIndex = h3ui.widgets[list.childIds[3]].props.current;
    }

    var data = {};
    Object.assign(data, filter, {pageSize, pageIndex});

    h3ui.services.brandListInfo(data).then(res => {
        if (res.success) {
            h3ui.widgets.FormList16.props.dataSource = {
                items: res.data.data,
                total: res.data.total
            }
        }
    })

}


function clickBrandRow(evt) {
    console.log(evt);

    var vendor = evt.data.row.org_fullname;
    var brand = evt.data.row.brand;

    h3ui.widgets.FormModelItem123.props.value = brand;
    h3ui.widgets.FormModelItem119.props.value = vendor;

    reloadList("FormList-saled");

    h3ui.widgets.Modal11.props.visible = false;


}


/***
 *  时间格式化
 */
function formatDate(value) {
    let date = new Date(value);
    let y = date.getFullYear();
    let MM = date.getMonth() + 1;
    MM = MM < 10 ? ('0' + MM) : MM;
    let d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    let m = date.getMinutes();
    m = m < 10 ? ('0' + m) : m;
    let s = date.getSeconds();
    s = s < 10 ? ('0' + s) : s;
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}
